# -*-coding:utf-8-*-
# 朝代,帝号,年号查询不和日历整合
# 用年号对应农历，公历对应农历，即可用公历查年号，或用年号查公历


from datetime import datetime, timedelta
from zhdate import ZhDate
import sys
import getopt
import string
import time


# 元组
'''
格里历（即公历）月份天数分布
'''
mday = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31


#注意,python中/的结果会保留小数点后面的数，//只保留整数
'''
用蔡勒公式计算一个日期属于星期几
'''
def whatweek(year, month, day):
    if month == 1 or month == 2:
        year = year - 1
        month = month + 12
    y = year % 100
    c = year // 100
    if year<= 1582 and month <= 10 and day <= 4:
        w = (y + y // 4 + c // 4 - 2 * c + (13 * (month + 1) // 5) + day + 3) % 7
    else:
        w = (y + y // 4 + c // 4 - 2 * c + (13 * (month + 1) // 5) + day - 1) % 7
    if w < 0:
        w += 7
    return w


#西历四年，罗马皇帝”奥古斯都帝“停闰，故该年二月仅有28天而不是29天
#西历1582年以前的闰年计算规则是”被4整除者即为闰年“，所以西元100,200,300，……，1400,1500年都是闰年
'''
判断是否闰年
'''
def is_leap(year):
    if year < 1582 and year != 4:
        return year % 4 == 0
    elif year == 4:
        return 0
    else:
        return year % 4 == 0 and year % 100 != 0 or year % 400 == 0     
    

'''
判断一个月份的天数
'''
def monthdays(year, month):
    if month != 2:
        month = month - 1
        return mday[month]
    month = month - 1
    return mday[month] + is_leap(year)


'''
截取农历日期字符串中的月份
'''
def cutdatemon(dt):
    i = 0
    while dt[i] != '年':
        i += 1
    if dt[i+1] != '十':
        return dt[i+1]
    else:
        return dt[i+1:i+3]


'''
截取农历日期字符串中的日份
'''
def cutdateday(dt):
    i = 0
    while dt[i] != '月':
        i += 1
    return dt[i+1:i+3]



def put_lunar(y, m, d):
    wd = whatweek(y, m, 1)
    mdays = monthdays(y, m)
    dt = datetime(y, m, d)
    date = ZhDate.from_datetime(dt).chinese()
    print("农历{}".format(date))
    print("    日    一    二    三    四    五    六")
    print("------------------------------------------")
    i = 0
    while i < wd:
        print("      ", end="")
        i = i + 1
    for x in range(1, mdays+1):
        if x == d:
            dt1 = ZhDate.from_datetime(datetime(y, m, x)).chinese()
            print("%s%4s%s" % ("\033[7m", cutdateday(dt1), "\033[0m"), end="")
        else:
            dt1 = ZhDate.from_datetime(datetime(y, m, x)).chinese()
            print("%4s" % cutdateday(dt1) , end="")
        wd = wd + 1
        if wd % 7 == 0:
            print("")
    if wd % 7 != 0:
        print("")
    return


def put_calendar(y, m, d):
    wd = whatweek(y, m, 1)
    mdays = monthdays(y, m)
    print(" 日 一 二 三 四 五 六")
    print("---------------------")
    i = 0
    while i < wd:
        print("   ", end="")
        i = i + 1
    for x in range(1, mdays+1):
        if x == d:
            print("{}{:3d}{}".format('\33[7m', x, '\033[0m'), end="")
        else:
            print("%3d" % x, end="")
        wd = wd + 1
        if wd % 7 == 0:
            print("")
    if wd % 7 != 0:
        print("")
    return

# 罗马教皇在1582年修改历法，将10月5日指定为10月15日，从而正式废止儒略历法，开始启用格里历法。
def put_calendar1582_10():
    print(" 日 一 二 三 四 五 六")
    print("---------------------")
    print("        1  2  3  4 15")
    print(" 16 17 18 19 20 21 22")
    print(" 23 24 25 26 27 28 29")
    print(" 30 31")

def main(argv):
    localtime = time.localtime(time.time())#一个列表
    y = localtime[0]
    m = localtime[1]
    d = localtime[2]

    try:
        opts, argv = getopt.getopt(
            argv, "hy:m:d:l", ["year=", "month=", "day=", "lunar"])
    except getopt.GetoptError:
        print('calendar.py -y <year> -m <month>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('calendar.py -y <year> -m <month>')
            sys.exit()
        elif opt in ("-y", "--year"):
            y = int(arg)
        elif opt in ("-m", "--month"):
            m = int(arg)
        elif opt in ("-d", "--day"):
            d = int(arg)
        elif opt in ("-l", "--lunar"):
            put_lunar(y, m, d)
            print("")

    print("公元{}年{}月".format(y, m))
    if y == 1582 and m == 10:
        put_calendar1582_10()
    else:
        put_calendar(y, m, d)


if __name__ == '__main__':
    main(sys.argv[1:])
